package com.cdshop.web.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Observable;

import javax.servlet.http.HttpSession;

import com.cdshop.dao.UserDAO;
import com.cdshop.entity.User;
import com.cdshop.web.SessionAttribute;

public final class AuthenticateService {

	protected final Observable loginObser = new Observable();
	protected final Observable logoutObser = new Observable();

	protected AuthenticateService() {
	}

	protected static AuthenticateService singleton = new AuthenticateService();

	public static AuthenticateService instance() {
		return singleton;
	}

	public boolean isLoggedIn(HttpSession session) {
		if (session == null)
			return false;
		return session.getAttribute(SessionAttribute.IDENTITY) != null;
	}

	public Identity getIdentity(HttpSession session) {
		return (Identity) session.getAttribute(SessionAttribute.IDENTITY);
	}

	public boolean login(HttpSession session, String username, String password) {
		if (session == null)
			return false;
		User user = authenticate(username, password);
		if (user != null) {
			Identity identity = new Identity(user);
			session.setAttribute(SessionAttribute.IDENTITY, identity);
			return true;
		} else {
			return false;
		}

	}

	public boolean logout(HttpSession session) {
		if (session == null)
			return true;
		session.removeAttribute(SessionAttribute.IDENTITY);
		return true;
	}

	protected User authenticate(String username, String password) {
		return UserDAO.instance().login(username, password);
	}

	public String hash(String value) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(value.getBytes());
			return HexCoder.encodeHexString(digest.digest());
		} catch (NoSuchAlgorithmException e) {
			return String.valueOf(value.hashCode());
		}
	}

}
